// HTTP 模块类型定义 (为了兼容性)
namespace http {
  export enum RequestMethod {
    GET = 'GET',
    POST = 'POST',
    PUT = 'PUT',
    DELETE = 'DELETE'
  }

  export interface HttpRequest {
    request(url: string, options?: any): Promise<any>;

    destroy(): void;
  }

  export function createHttp(): HttpRequest {
    return {
      request: async (url: string, options?: any) => {
        // 使用原生 fetch API 作为备用方案
        console.log(`HTTP Request: ${options?.method || 'GET'} ${url}`);
        const httpRequest = http.createHttp();
        const response = await httpRequest.request(url, {
          method: options?.method || 'GET',
          headers: options?.header || {},
          body: options?.extraData
        });

        const result = await response.text();
        return { result };
      },
      destroy: () => {
      }
    };
  }
}

import {
  OrderModel,
  UserModel,
  CreateOrderRequest,
  UpdateOrderStatusRequest,
  AssignOrderRequest,
  EvaluateOrderRequest,
  OrderQueryParams,
  PagedResponse,
  ApiResponse,
  StatisticsModel
} from '../model/OrderModel';
import { OrderStatus, UserRole, OrderType, UrgencyLevel } from '../common/enums';
import { StorageManager } from '../common/storage';
import { AppConfig } from '../common/config';

/**
 * HTTP请求参数接口
 */
interface HttpRequestParams {
  method: http.RequestMethod;
  header: Record<string, string>;
  extraData?: string;
}

/**
 * API 服务类
 * 连接到后端REST API服务器，后端连接MongoDB数据库
 */
export class ApiService {
  private static instance: ApiService;
  private baseUrl: string;
  private storageManager: StorageManager;

  private constructor() {
    this.baseUrl = AppConfig.BACKEND_URL;
    this.storageManager = StorageManager.getInstance();
    console.log(`API Service initialized with backend URL: ${this.baseUrl}`);
  }

  public static getInstance(): ApiService {
    if (!ApiService.instance) {
      ApiService.instance = new ApiService();
    }
    return ApiService.instance;
  }

  /**
   * 设置服务器地址
   */
  public setBaseUrl(url: string): void {
    this.baseUrl = url;
  }

  /**
   * 初始化API服务 - 配置后端服务器地址
   * @param backendUrl 后端REST API服务器地址
   */
  public initialize(backendUrl: string): void {
    this.baseUrl = backendUrl;
    console.log(`API Service initialized with backend URL: ${backendUrl}`);
  }

  /**
   * HTTP 请求封装
   */
  private async httpRequest<T>(
    method: http.RequestMethod,
    endpoint: string,
    data?: object
  ): Promise<ApiResponse<T>> {
    try {
      const httpRequest = http.createHttp();
      const url = `${this.baseUrl}${endpoint}`;

      const requestParams: HttpRequestParams = {
        method: method,
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${await this.getAuthToken()}`
        }
      };

      if (data) {
        requestParams.extraData = JSON.stringify(data);
      }

      console.log(`Making HTTP request: ${method} ${url}`);
      const response = await httpRequest.request(url, requestParams);

      let result: ApiResponse<T>;
      if (typeof response.result === 'string') {
        result = JSON.parse(response.result) as ApiResponse<T>;
      } else {
        result = {
          success: false,
          data: {} as T,
          message: '响应格式错误',
          code: -1
        };
      }

      // 处理登录响应中的token（从header获取）
      if (endpoint === '/auth/login' && result.success && response.header && response.header['authorization']) {
        const token = response.header['authorization'].replace('Bearer ', '');
        await this.storageManager.setValue('auth_token', token);
        console.log('Token saved from login response header');
      }

      httpRequest.destroy();
      return result;
    } catch (error) {
      console.error('HTTP request failed:', error);
      return {
        success: false,
        data: {} as T,
        message: `网络请求失败: ${error}`,
        code: -1
      };
    }
  }

  /**
   * 获取认证令牌
   */
  private async getAuthToken(): Promise<string> {
    const token = await this.storageManager.getValue('auth_token', '');
    return typeof token === 'string' ? token : '';
  }

  /**
   * 用户登录
   */
  public async login(phone: string, password: string): Promise<ApiResponse<UserModel>> {
    return await this.httpRequest<UserModel>(http.RequestMethod.POST, '/auth/login', { phone, password });
  }

  /**
   * 获取工单列表
   */
  public async getOrders(params: OrderQueryParams): Promise<ApiResponse<PagedResponse<OrderModel>>> {
    const queryParams = this.buildQueryString(params);
    return await this.httpRequest<PagedResponse<OrderModel>>(http.RequestMethod.GET, `/orders?${queryParams}`);
  }

  /**
   * 创建工单
   */
  public async createOrder(orderData: CreateOrderRequest): Promise<ApiResponse<OrderModel>> {
    return await this.httpRequest<OrderModel>(http.RequestMethod.POST, '/orders', orderData);
  }

  /**
   * 更新工单状态
   */
  public async updateOrderStatus(updateData: UpdateOrderStatusRequest): Promise<ApiResponse<OrderModel>> {
    return await this.httpRequest<OrderModel>(http.RequestMethod.PUT, `/orders/${updateData.orderId}/status`,
      updateData);
  }

  /**
   * 派单
   */
  public async assignOrder(assignData: AssignOrderRequest): Promise<ApiResponse<OrderModel>> {
    return await this.httpRequest<OrderModel>(http.RequestMethod.PUT, `/orders/${assignData.orderId}/assign`,
      assignData);
  }

  /**
   * 工单评价
   */
  public async evaluateOrder(evaluateData: EvaluateOrderRequest): Promise<ApiResponse<OrderModel>> {
    return await this.httpRequest<OrderModel>(http.RequestMethod.PUT, `/orders/${evaluateData.orderId}/evaluate`,
      evaluateData);
  }

  /**
   * 获取统计数据
   */
  public async getStatistics(): Promise<ApiResponse<StatisticsModel>> {
    return await this.httpRequest<StatisticsModel>(http.RequestMethod.GET, '/statistics');
  }

  /**
   * 构建查询字符串
   */
  private buildQueryString(params: OrderQueryParams): string {
    const queryParts: string[] = [];

    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        queryParts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
      }
    });

    return queryParts.join('&');
  }
}